package com.plat.api.api.action;

import java.math.BigDecimal;
import java.util.*;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.plat.api.anonation.NoToken;
import com.plat.api.anonation.Token;
import com.plat.api.common.RespCode;
import com.plat.api.dao.api.PlatWechatLiveRoomDao;
import com.plat.api.dao.api.TokenDao;
import com.plat.api.dao.api.UserDao;
import com.plat.api.entity.api.PlatWechatLiveRoomEntity;
import com.plat.api.exception.PlatException;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 * User: shish
 * Date: 2020/7/11
 * Time: 13:28
 * Description: 直播相关接口
 */
@Slf4j
@Service
@Token
public class PlatLiveAction {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private PlatWechatLiveRoomDao platWechatLiveRoomDao;

    /**
     * 开房间直播
     */
    @NoToken
    public JSONObject publish(JSONObject jsonObject) throws WxErrorException {
        String accessToken = wxMaService.getAccessToken();
        JSONObject param = jsonObject.getJSONObject("body");

        String name = param.getString("name");
        String coverImg = param.getString("coverImg");
        Date startTime = param.getDate("startTime");
        Date endTime = param.getDate("endTime");
        String anchorName = param.getString("anchorName");
        String anchorWechat = param.getString("anchorWechat");
        String shareImg = param.getString("shareImg");
        String coverImgUrl = param.getString("coverImgUrl");
        String shareImgUrl = param.getString("shareImgUrl");
        Integer type = param.getInteger("type");
        Integer screenType = param.getInteger("screenType");
        Integer closeLike = param.getInteger("closeLike");
        Integer closeGoods = param.getInteger("closeGoods");
        Integer closeComment = param.getInteger("closeComment");
        String detail = param.getString("detail");
        Integer isFree = param.getInteger("isFree");
        Double price = param.getDouble("price");
        JSONObject jsonMap = new JSONObject();
        Long st = startTime.getTime() / 1000;
        Long et =  endTime.getTime() / 1000;
        jsonMap.put("name", name);
        jsonMap.put("coverImg", coverImg);
        jsonMap.put("startTime", st);
        jsonMap.put("endTime", et);
        jsonMap.put("anchorName", anchorName);
        jsonMap.put("anchorWechat", anchorWechat);
        jsonMap.put("shareImg", shareImg);
        jsonMap.put("type", type);
        jsonMap.put("screenType", screenType);
        jsonMap.put("closeLike", closeLike);
        jsonMap.put("closeGoods", closeGoods);
        jsonMap.put("closeComment", closeComment);
        JSONObject json = new JSONObject();
        String js = jsonMap.toJSONString();
        try {
            String result = HttpUtil.post("https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token=" + accessToken, js);
            JSONObject res = JSONObject.parseObject(result);
             if (res.getLong("roomId")!=null){
                 PlatWechatLiveRoomEntity entity = new PlatWechatLiveRoomEntity();
                 entity.setName(name);
                 entity.setCoverImg(coverImg);
                 entity.setStartTime(startTime);
                 entity.setEndTime(endTime);
                 entity.setAnchorName(anchorName);
                 entity.setAnchorWechat(anchorWechat);
                 entity.setShareImg(shareImg);
                 entity.setType(type);
                 entity.setScreenType(screenType);
                 entity.setCloseLike(closeComment);
                 entity.setCloseGoods(closeGoods);
                 entity.setCloseComment(closeComment);
                 entity.setPassword("");
                 entity.setCoverImgUrl(coverImgUrl);
                 entity.setShareImgUrl(shareImgUrl);
                 entity.setDetail(detail);
                 entity.setIsTop(0);
                 entity.setDetail(detail);
                 entity.setImageUrls("");
                 entity.setIsCheck(0);
                 entity.setRoomId(res.getLong("roomId"));
                 entity.setIsOffonline(1);
                 entity.setIsFree(isFree);
                 entity.setPrice(price);
                 entity.setPoster("");
                 entity.setMediaUrl("");
                 platWechatLiveRoomDao.insert(entity);
                 json.put("object", entity);
             }else {
                 String descMsg = getDesc(res);
                 throw new PlatException(RespCode.WEIXIN_CREATE_LIVE_ERROR.getError_msg(), RespCode.WEIXIN_CREATE_LIVE_ERROR.getCode(),descMsg);
             }
        } catch (PlatException e) {
            e.printStackTrace();
            log.info("[开通房间直播失败，请联系管理员]");
            throw e;
        }
        return json;
    }

    private String getDesc(JSONObject res) {
        String msg = "";
        if (res.getString("errcode").equals("-1")){
            msg=   "微信系统错误";
        }
        if (res.getString("errcode").equals("1")){
            msg =  "未创建直播间";
        }
        if (res.getString("errcode").equals("300029")){
            msg =  "主播昵称违规";
        }
        if (res.getString("errcode").equals("300028")){
            msg =  "房间名称违规";
        }
        return msg;
    }

    @NoToken
    public JSONObject getLive(JSONObject jsonObject) {
        JSONObject param = jsonObject.getJSONObject("body");
        Integer id = param.getInteger("id");
        LambdaQuery<PlatWechatLiveRoomEntity> query = platWechatLiveRoomDao.getSQLManager().lambdaQuery(PlatWechatLiveRoomEntity.class);
        List<PlatWechatLiveRoomEntity> list = query.andEq("id", id).page(1, 1).getList();
        JSONObject json = new JSONObject();
        json.put("object", list.get(0));
        return json;
    }
    @NoToken
    public JSONObject getLiveList(JSONObject jsonObject) throws WxErrorException {
        String accessToken = wxMaService.getAccessToken();
        JSONObject param = jsonObject.getJSONObject("body");
        Integer page = param.getInteger("page");
        Integer pageSize = param.getInteger("pageSize");
        LambdaQuery<PlatWechatLiveRoomEntity> query = platWechatLiveRoomDao.getSQLManager().lambdaQuery(PlatWechatLiveRoomEntity.class);
        List<PlatWechatLiveRoomEntity> list = query.orderBy("id desc").page(page, pageSize).getList();

        JSONArray res = new JSONArray();
        try {
            JSONObject map = new JSONObject();
            map.put("start", page-1);
            map.put("limit", pageSize);
            String result = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" + accessToken, map.toJSONString());
            res = JSONObject.parseObject(result).getJSONArray("room_info");
        } catch (Exception e) {
            log.info("[获取房间号码失败]");
        }
        List<PlatWechatLiveRoomEntity> list1 = new ArrayList<>();
        for (PlatWechatLiveRoomEntity entity : list) {
            if (res!=null){
                for (Object obj : res) {
                    JSONObject jsobj = (JSONObject) obj;
                    if (String.valueOf(entity.getRoomId())!=null){
                         if (entity.getRoomId()==jsobj.getLong("roomid")){
                             Integer liveStatus = jsobj.getInteger("live_status");
                             String liveStatusName = "直播状态";
                             entity.setLiveStatus(liveStatus);
                             if (liveStatus==101){
                                 liveStatusName = "直播中";
                             }
                             if (liveStatus==102){
                                 liveStatusName = "未开始";
                             }
                             if (liveStatus==103){
                                 liveStatusName = "已结束";
                             }
                             if (liveStatus==104){
                                 liveStatusName = "禁播";
                             }
                             if (liveStatus==105){
                                 liveStatusName = "暂停";
                             }
                             if (liveStatus==106){
                                 liveStatusName = "异常";
                             }
                             if (liveStatus==107){
                                 liveStatusName="已过期";
                             }
                             entity.setStart_Time(DateUtil.format(entity.getStartTime(),"yyyy-MM-dd hh:mm:ss"));
                             entity.setEnd_Time(DateUtil.format(entity.getEndTime(),"yyyy-MM-dd hh:mm:ss"));
                             entity.setLiveStatusName(liveStatusName);
                             list1.add(entity);
                         }
                    }
                }
            }
        }
        JSONObject json = new JSONObject();
        json.put("list", list1);
        return json;
    }
}
